﻿// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";
    var nav = WinJS.Navigation;

    WinJS.UI.Pages.define("/pages/loaded/loadedInfo.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            var text = Data.getText();

            if (text == null || text == "") {
                text = "<h2>Няма допълнителна информация!</h2>"
            }

            var container = document.getElementById("content");
            container.innerHTML = text;
            Data.saveText("");

            var backButton = document.getElementById("cmdBack").winControl;
            var homeButton = document.getElementById("cmdHome").winControl;
            var saveBtn = document.getElementById("saveInfo");
            var saveTemplateBtn = document.getElementById("saveInfoTemplate");
            var printBtn = document.getElementById("printInfoTemplate");

            printBtn.addEventListener("click", PrintButtonHandler, false);

            registerForPrintContract();

            saveTemplateBtn.addEventListener("click", function () {

                var savePicker = new Windows.Storage.Pickers.FileSavePicker();
                savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;

                savePicker.defaultFileExtension = ".txt"
                savePicker.fileTypeChoices.insert("Text File", [".txt"]);
                savePicker.suggestedFileName = "New Template Document";

                savePicker.pickSaveFileAsync().then(function (file) {
                    var textToWrite = text;
                    Windows.Storage.FileIO.writeTextAsync(file, textToWrite, Windows.Storage.Streams.UnicodeEncoding.utf8);
                });
            });

            saveBtn.addEventListener("click", function () {

                var savePicker = new Windows.Storage.Pickers.FileSavePicker();
                savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;

                savePicker.defaultFileExtension = ".rtf"
                savePicker.fileTypeChoices.insert("Text File", [".rtf"]);
                savePicker.suggestedFileName = "New Text Document";

                savePicker.pickSaveFileAsync().then(function (file) {

                    var patt2 = /(<([^>]+)>)/ig;
                    text = text.replace(patt2, " ");

                    var textToWrite = text;
                    Windows.Storage.FileIO.writeTextAsync(file, textToWrite, Windows.Storage.Streams.UnicodeEncoding.utf8);
                });
            });

            backButton.addEventListener("click", function () {
                nav.back(1);
            });

            homeButton.addEventListener("click", function () {
                nav.navigate("/pages/home/home.html");
            });
        }
    });

    function registerForPrintContract() {
        var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
        printManager.onprinttaskrequested = onPrintTaskRequested;
        WinJS.log && WinJS.log("Print Contract registered. Use Print button to print.", "sample", "status");
    }

    /// <summary>
    /// Print event handler for printing via the PrintManager API. The user has to manually invoke
    /// the print charm after this function is executed.
    /// </summary>
    /// <param name="printEvent" type="Windows.Graphics.Printing.PrintTaskRequest">
    /// The event containing the print task request object.
    /// </param>
    function onPrintTaskRequested(printEvent) {
        var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
            args.setSource(MSApp.getHtmlPrintDocumentSource(document));

            // Register the handler for print task completion event
            printTask.oncompleted = onPrintTaskCompleted;
        });
    }

    /// <summary>
    /// Print Task event handler is invoked when the print job is completed.
    /// </summary>
    /// <param name="printTaskCompletionEvent" type="Windows.Graphics.Printing.PrintTaskCompleted">
    /// The event containing the print task completion object.
    /// </param>
    function onPrintTaskCompleted(printTaskCompletionEvent) {
        // Notify the user about the failure
        if (printTaskCompletionEvent.completion === Windows.Graphics.Printing.PrintTaskCompletion.failed) {
            WinJS.log && WinJS.log("Failed to print.", "sample", "error");
        }
    }

    /// <summary>
    /// Executed just before printing.
    /// </summary>
    var beforePrint = function () {
        // Replace with code to be executed just before printing the current document:
    };

    /// <summary>
    /// Executed immediately after printing.
    /// </summary>
    var afterPrint = function () {
        // Replace with code to be executed immediately after printing the current document:
    };

    function PrintButtonHandler() {
        // Optionally, functions to be executed immediately before and after printing can be configured as following:
        window.document.body.onbeforeprint = beforePrint;
        window.document.body.onafterprint = afterPrint;

        // If the print contract is registered, the print experience is invoked.
        Windows.Graphics.Printing.PrintManager.showPrintUIAsync();
    }

})();
